<template>
  <div>
    <section class="handle-buttons">
      <el-button @click="previewForm" type="primary" :disabled="!article.id">预览</el-button>
      <el-button @click="submitForm" type="success">保存</el-button>
      <el-button @click="deleteForm" type="danger" :disabled="!article.id">删除</el-button>
    </section>
    <AddForm v-model="article" />
    <WangEditor v-model="article.content" :height="300" />
  </div>
</template>

<script setup lang="ts">
import AddForm from './form/addForm.vue';
import articleApi from '@/apis/article';
import type { ArticleApiType } from '@/apis/article/namespace';
import { RouterEnum } from '@/enum';
import { debounceFunc } from '@/hooks/useDebounce';

// 路由信息
const route = useRoute();
const router = useRouter();

// 获取文章详情
const articleId = route.query.articleId as string;

// 文章详情数据
const article = ref<ArticleApiType.UpdateRequest>({
  id: '',
  title: '',
  preview: '',
  description: '',
  content: '',
  categoryId: '',
  status: false,
});

// 获取文章详情
onMounted(async () => {
  // 如果没有文章ID，则不执行
  if (!articleId) return;

  // 获取文章详情
  const data = await articleApi.detail({ id: articleId });
  article.value.id = articleId;
  article.value.title = data.title ?? '';
  article.value.preview = data.preview ?? '';
  article.value.description = data.description ?? '';
  article.value.content = data.content ?? '';
  article.value.categoryId = data.category?.id ?? '';
  article.value.status = data.status ?? false;
});

// 提交表单
const submitForm = debounceFunc(async () => {
  const { id, ...params } = article.value;
  if (!id) {
    const res = await articleApi.create(params);
    article.value.id = res.id;
  } else {
    await articleApi.update(article.value);
  }
}, 500);

const previewForm = () => {
  router.push({ name: RouterEnum.ARTICLE_DETAIL, query: { articleId: article.value.id } });
};

const deleteForm = () => {
  const params = { ids: [article.value.id ?? ''] };
  ElMessageBox.confirm('确认删除该文章吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await articleApi.delete(params);
    article.value = {
      id: '',
      title: '',
      preview: '',
      content: '',
      categoryId: '',
      status: false,
    };
  });
};
</script>

<style scoped lang="scss">
.handle-buttons {
  @apply mb-1 p-4 border border-gray-300 rounded-md;
}
</style>
